package com.zmn.oms.third.callcenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.zmn.common.utils.MethodSignUtils;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.manager.common.cat.http.MonitorHttpsUtils;
import com.zmn.oms.model.entity.callinfo.CallAddInfo;
import com.zmn.oms.third.baidu_dtw.BaiduDtwConsts;
import com.zmn.oms.third.base.dto.api.ApiInvokResult;
import com.zmn.oms.third.callcenter.dto.PushOrderCluesDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;

/**
 * 类描述：呼叫中心API接口调用器
 *
 * @author lhl
 * @date 2020/02/19 1:47
 */
@Slf4j
public final class CallCenterApiInvoker {

    /**
     * 调用api
     * @param pushOrderCluesDTO
     * @return
     */
    public static ApiInvokResult apiInvoke(PushOrderCluesDTO pushOrderCluesDTO) {
        String url = CallCenterConstants.API_URL;

        CallAddInfo callAddInfo = new CallAddInfo();
        BeanMapper.copy(pushOrderCluesDTO, callAddInfo);
        callAddInfo.setCustomerName(pushOrderCluesDTO.getUserName());
        callAddInfo.setCustomerNumber(pushOrderCluesDTO.getUserPhone());
        callAddInfo.setOperator("系统");
        // outRequire：AUTO_OUT（自动外呼），NOT_AUTO_OUT（不自动外呼）
        callAddInfo.setOutRequire("AUTO_OUT");
        /*
            sourceType：
            YI_LIAO(易聊推送),
            CMS(cms推送),
            WU_BA_TONG_CHENG(58同城),
            KUAI_YI_XIOU(快益修),
            DING_DING_XIAO_XI(钉钉消息),
            REN_GONG_LU_DAN(人工录单),
            QU_DAO(渠道推送),
         */
        callAddInfo.setSourceType("QU_DAO");

        Map<String, Object> body  = Maps.newHashMap();
        Map<String, CallAddInfo> params  = Maps.newHashMap();
        params.put("dio", callAddInfo);
        body.put("body", params);
        String json = JSON.toJSONString(body);

        ApiInvokResult result = null;
        String response = null;
        try {
            log.info("[{}-API] <Request> Url:[{}] RequestBody:[{}]", CallCenterConstants.NAME_CALL_CENTER_API,
                    url, json);
            //response = HttpUtil.httpsPost(url, json);
            response = MonitorHttpsUtils.postJson(url, json);
            log.info("[{}-API] <Response> ResponseBody:[{}]", CallCenterConstants.NAME_CALL_CENTER_API, response);

            result = parseResult(response);
        } catch (Exception e) {
            result = new ApiInvokResult();
            result.setSuccess(false);
            result.setMsg(e.getMessage());

            log.info("[{}-API] Request failed:[{}]", CallCenterConstants.NAME_CALL_CENTER_API, e.getMessage());
            log.error(e.getMessage(), e);
        }

        return result;
    }
    /**
     * 调用api
     * @param path
     * @param pushOrderCluesDTO
     * @return
     */
    public static ApiInvokResult apiInvokeOld(String path, PushOrderCluesDTO pushOrderCluesDTO) {
        String url = CallCenterConstants.API_URL_OLD + path;

        Map<String, String> params = JSONObject.parseObject(JSON.toJSONString(pushOrderCluesDTO),
                new TypeReference<Map<String, String>>() {});
        params.put("sign", MethodSignUtils.sign(params, CallCenterConstants.SECRET));

        String json = JSON.toJSONString(params);
        ApiInvokResult result = null;
        String response = null;
        try {
            log.info("[{}-API] <Request> Url:[{}] RequestBody:[{}]", CallCenterConstants.NAME_CALL_CENTER_API,
                    url, json);
            response = MonitorHttpsUtils.postForm(url, params);
            log.info("[{}-API] <Response> ResponseBody:[{}]", CallCenterConstants.NAME_CALL_CENTER_API, response);

            result = parseResult(response);
        } catch (Exception e) {
            result = new ApiInvokResult();
            result.setSuccess(false);
            result.setMsg(e.getMessage());

            log.info("[{}-API] Request failed:[{}]", CallCenterConstants.NAME_CALL_CENTER_API, e.getMessage());
            log.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * 解析请求结果字符串
     * @param response
     * @return
     */
    private static ApiInvokResult parseResult(String response) {
        // TODO -lhl 解析请求结果字符串
        CallCenterApiResult callCenterApiResult = JSON.parseObject(response, CallCenterApiResult.class);

        ApiInvokResult result = new ApiInvokResult();
        result.setSuccess(Objects.equals(200, callCenterApiResult.getStatus()));
        result.setMsg(callCenterApiResult.getMessage());
        return result;
    }

    public static void main(String[] args) {
        // 测试环境
        CallCenterConstants.API_URL_OLD = "https://test2-cc-api.xiujiadian.com:8899";
        CallCenterConstants.SECRET = "867D0B5FBEBFEF9818DF9F39E87EAA9E";
        CallCenterConstants.API_URL = "http://test2-gateway-api.xiujiadian.com/ccc/api/clue/addClue";
        // 线上环境
        //CallCenterConstants.API_URL_OLD = "https://cc-api.xiujiadian.com:8899";
        //CallCenterConstants.SECRET = "0D88803ACC26F6E838EFA811095D6350";
        //CallCenterConstants.API_URL = "http://gateway-api.xiujiadian.com/ccc/api/clue/addClue";

        PushOrderCluesDTO pushOrderCluesDTO = new PushOrderCluesDTO();
        pushOrderCluesDTO.setChannelId(BaiduDtwConsts.CHANNEL_ID_3);
        pushOrderCluesDTO.setChannelName(BaiduDtwConsts.NAME);

        pushOrderCluesDTO.setUserPhone("18010491280");
        //pushOrderCluesDTO.setUserName("九戒");
        //pushOrderCluesDTO.setRemark("挂机空调维修，北土城西路7号，元大都7号B-903");
        //pushOrderCluesDTO.setAddress("挂机空调维修，北土城西路7号，元大都7号B-903");

        ApiInvokResult apiInvokResult = apiInvokeOld(CallCenterConstants.PATH_ADD_ORDER, pushOrderCluesDTO);
        //ApiInvokResult apiInvokResult = apiInvoke(pushOrderCluesDTO);
        System.out.println(JSON.toJSONString(apiInvokResult));
    }

    @Data
    private static class CallCenterApiResult {
        private Long timestamp;
        private Integer status;
        private String error;
        private String message;
        private String path;
    }
}
